/**
 * @description 工具服务
 * @author anytao
 * @created 2016-08-24
 * @version 1.0
 */

'use strict';

import request from 'request';
import imageSize from 'image-size';

export default class extends think.service.base {

    /**
     * init
     * @return {}         []
     */
    init(...args) {
        super.init(...args);
    }

    /**
     * 根据ip地址获取地理位置信息
     * 
     */
    getIpinfo(ip) {

        let url = "http://ip.taobao.com/service/getIpInfo.php?ip=" + ip;

        let getIpinfo = (url) => {
            let deferred = think.defer();
            request({
                url: url
            }, function(err, response, body) {
                if (err) {
                    deferred.reject(err);
                } else {
                    deferred.resolve(JSON.parse(body).data);
                }
            });
            return deferred.promise;
        }
        return getIpinfo(url);
    }

    /**
     * 根据图片链接地址获取图片尺寸信息
     * 返对象
     * { width: 427, height: 100, type: 'svg' }
     */
    async getImageSize(url) {

        let options = {
            url: url,
            encoding: null
        };

        let getImageSize = (url) => {
            let deferred = think.defer();
            request.get(options, function(err, response, body) {
                if (err) {
                    deferred.reject(err);
                } else {
                    deferred.resolve(imageSize(body));
                }
            });
            return deferred.promise;
        }
        return await getImageSize(url);
    }
}